# coding: UTF-8 #
import urllib2,time,MySQLdb,random,base64,socket
#import sys
#reload(sys)
#sys.setdefaultencoding("gbk")

B_id_S=1
B_id_E=3465
socket.setdefaulttimeout(30)
conn=MySQLdb.connect(host='192.168.164.137',user='root',passwd='root',db='wy',port=3306,charset="utf8")
cur=conn.cursor()
log=open("/root/wy_log.txt","w")

def R_Agent():#Bypass firewalls
    USER_AGENTS = [
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
    "Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
    "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
    "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
    "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
    "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
    "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
    "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5",
    "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
    "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52",
    "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36",
    "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
    "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
    "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",
    "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
    "Mozilla/5.0 (Windows NT 6.1;rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
    "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11",
    "Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser)",
    ]
    return USER_AGENTS[(random.randint(0,999)%len(USER_AGENTS))]

def IMG_process(a):#DOWLAND IMG TO LOCAL AND CHANGE IMG URL
    msg=a
    if (msg.find('<p class="detail usemasaic"><a href="')==-1):
        return msg
    msg_1=msg.split('<p class="detail usemasaic"><a href="')
    if len(msg_1)<2:
        num=2
    else:
        num=len(msg_1)
    for i in range(1,num):
        msg_2=msg_1[i].split('" target="_blank"><img src="')
        msg_imgtype=msg_2[0].split('/').pop().split('.').pop()
        if (msg_2[0].find("http://static.wooyun.org/wooyun")==-1):
            msg_3="http://www.wooyun.org"+msg_2[0]
        else:
            msg_3=msg_2[0]
        msg_imgbase64=base64.b64encode(urllib2.urlopen(msg_3).read())
        msg_imgdata=msg_2[1].split('" alt="" width="600" onerror="javascript:errimg(this);"/>')[0]
        msg=msg.replace(msg_2[0],"",1)
        msg=msg.replace(msg_imgdata,"data:image/"+msg_imgtype+";base64,"+msg_imgbase64,1)
    return msg

def S_Bug_Sql(z,a,b,c,d,e,f,g,h):#SAVE BUG INFO INTO DATEBASES
    global cur,conn
    sql='INSERT INTO `wooyun`(`wybug_id`,`wybug_description`, `wybug_title`, `wybug_keywords`, `wybug_corp`, `wybug_date`, `wybug_type`, `wybug_detail`, `wybug_poc`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)'
    bb=cur.execute(sql,(z,a,b,c,d,e,f,g,h))
    conn.commit()

def G_Bug_Date(a):#GET BUG INFO
    msg_wooyunid=a.split('/').pop()
    log.write(msg_wooyunid+"\r\t")
    global cur,conn
    url='http://www.wooyun.org'+str(a)
    req = urllib2.Request(url)
    req.add_header('User-Agent', R_Agent())
    try:
        s='细节向公众公开'
        retrys=0
        msg=""
        for i in range(0,3):
            msg=urllib2.urlopen(req).read()
            if (msg.find(s)==-1):
                print "NOT OPEN" +str(i+1)
                time.sleep(0.5)
            else:
                retrys=1
                break
        if retrys==0:
            return 1
        sql='SELECT * FROM `wooyun` WHERE `wybug_id`='+"'"+msg_wooyunid+"'"
        if (cur.execute(sql)<>0):
            print msg_wooyunid+" exist"
            return 1
        msg_tittle=msg.split("<h3 class='wybug_title'>")[1].split("</h3>")[0].replace(' ','').replace('	','')[15:]
        if msg_tittle.find('<imgsrc="/images/credit.png"')<>-1:
            msg_tittle=msg_tittle.split('<imgsrc="/images/credit.png"')[0]
        msg_keywords=msg.split('<meta name="keywords" content="')[1].split('"/>')[0].replace(' ','').replace('	','')
        msg_description=msg.split('<meta name="description" content="')[1].split('|WooYun')[0]
        msg_crop=msg.split('<a href="http://www.wooyun.org/corps/')[1].split('">')[1].split('</a>')[0].replace(' ','').replace('	','').replace('\r\n','')
        msg_type=msg.split("<h3 class='wybug_type'>")[1].split('</h3>')[0][15:].replace(' ','').replace('	','')
        msg_data=msg.split("<h3 class='wybug_date'>")[1].split('</h3>')[0][15:].replace('	','')
        msg_detail=msg.split("<div class='wybug_detail'>")[1].split('</div>')[0].replace('			','')
        msg_poc=msg.split("<div class='wybug_poc'>")[1].split('</div>')[0].replace('			','')
        try:
            msg_detail=IMG_process(msg_detail)
            msg_poc=IMG_process(msg_poc)
        except:
            print "img error"
            return 0
        S_Bug_Sql(msg_wooyunid,msg_description,msg_tittle,msg_keywords,msg_crop,msg_data,msg_type,msg_detail,msg_poc)
        print msg_wooyunid+" success"
    except urllib2.URLError, e:
        print e.reason
        log.write(str(e.reason)+"\r\n")
    except socket.error , e:
        print "socket error"
        log.write("socket error \r\n")

def G_Bug_Url(a):#GET BUS URL
    time.sleep(1)
    req = urllib2.Request(a)
    req.add_header('User-Agent', R_Agent())
    try:
        temp=""
        for iiii in range(0,10):
            temp=urllib2.urlopen(req).read()
            if temp.find('<table class="listTable">')<>-1:
                break
            else:
                time.sleep(1)
        msg=(((temp.split('<table class="listTable">'))[1].split('</table'))[0].split('<tbody>'))[1].replace('\t','')
        bugs=msg.split('<td><a href="')
        for i in range(0,len(bugs)):
            if (i%2==1):
                G_Bug_Date(bugs[i].split('">')[0])
    except urllib2.URLError, e:
        print e.reason
        log.write(str(e.reason)+"\r\n")

def geturl(a,b):#GET BUG LIST
    for i in range(a-1,b+1)[::-1]:
        print i
        url='http://www.wooyun.org/bugs/page/'+str(i)
        try:
            G_Bug_Url(url)
            log.write(str(i)+"\r\n")
        except:
            log.write(str(i)+" error \r\n")

geturl(B_id_S,B_id_E)
cur.close()
conn.close()
log.close()
